package com.myblog.controller;


import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.myblog.common.lang.Result;
import com.myblog.entity.Blog;
import com.myblog.entity.BlogTags;
import com.myblog.entity.Tag;
import com.myblog.service.BlogTagsService;
import com.myblog.service.TagService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author From:星羽恒
 * @since 2021-11-24
 */
@RestController
@RequestMapping("/tag")
public class TagController {

    @Autowired
    TagService tagService;

    @Autowired
    BlogTagsService blogTagsService;

    @GetMapping("/tags")
    public Result getTagList(){
        //先返回前面几个即可
        List<Tag> tagList = (tagService.page(new Page(1,4), new QueryWrapper<Tag>().orderByAsc("id"))).getRecords();

        Map<Long,Integer> tagMap = new HashMap<>();
        for(Tag tempTag : tagList){
            Long tagId = tempTag.getId();
            if(!tagMap.containsKey(tagId)){
                int count = blogTagsService.count(new QueryWrapper<BlogTags>().eq("tags_id",tagId));
                tagMap.put(tagId,count);
            }
        }

        return Result.succ(MapUtil.builder()
                .put("tagList",tagList)
                .put("tagCountMap",tagMap)
                .map()
        );
    }

    @GetMapping("/allTags")
    public Result getAllTagList(){
        //先返回前面几个即可
        List<Tag> tagList = tagService.list();

        Map<Long,Integer> tagMap = new HashMap<>();
        for(Tag tempTag : tagList){
            Long tagId = tempTag.getId();
            if(!tagMap.containsKey(tagId)){
                int count = blogTagsService.count(new QueryWrapper<BlogTags>().eq("tags_id",tagId));
                tagMap.put(tagId,count);
            }
        }

        return Result.succ(MapUtil.builder()
                .put("tagList",tagList)
                .put("tagCountMap",tagMap)
                .map()
        );
    }

    @PostMapping("/addTag")
    public Result addNewTag(@RequestBody Tag newTag){
        tagService.saveOrUpdate(newTag);
        return Result.succ(newTag);
    }

}
